package com.acme.service.bank;


import com.acme.domain.account.*;
import com.acme.domain.bank.Bank;
import com.acme.domain.client.*;
import com.acme.exceptions.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.MatchResult;

class BankDataLoaderService {

	private static Client client;
	
	public static void load(final Bank bank, final String path)
			throws IOException,FileNotFoundException {
		Scanner sc;
		try {
			sc = new Scanner (new File(path));
		} catch (FileNotFoundException ex) {
			throw new FileNotFoundException("Feed file not found!");
		} catch (NullPointerException ex){
			throw new IOException("-loadfeed missed");
		}
		while (sc.hasNextLine()){
			sc.findInLine("accounttype=(\\w);balance=(\\d+);overdraft=(\\d+);name=(\\w+);gender=(\\w+);");
			MatchResult result = sc.match();
			try{
				parse(result);
				bank.addClient(client);
			} catch (ClientAlreadyExistsException e){
				System.out.println("This client is already exists. Skipping..");
			} catch (ClientCountLimitException e){
				System.out.println("Reached client limit... stopped");
				break;
			}

			if ( sc.hasNextLine())
				sc.nextLine();
		}
		sc.close();
	}
	
	private static void parse(final MatchResult result) throws IOException{
		double currentBalance = Double.parseDouble(result.group(2));
		double currentOverdraft = Double.parseDouble(result.group(3));
		Gender gen;
		switch (result.group(5)){
		case "m":
			gen = Gender.MALE;
			break;
		case "f":
			gen = Gender.FEMALE;
			break;
		default:
			throw new IOException("Wrong gender");	
		}

		switch (result.group(1)){
			case "c":
				client = new Client (
					new CheckingAccount(currentBalance, currentOverdraft),
					gen,
					result.group(4)
				);
				break;
			case "s":
				client = new Client (
					new SavingsAccount(currentOverdraft),
					gen,
					result.group(4)
				);
				break;
			default:
				throw new IOException("Account file error in feed file");
		}
	}
}
